package com.zy.mydemo.api.controller;

import com.zy.mydemo.api.service.UserService;
import com.zy.mydemo.common.entity.UserEntity;
import com.zy.mydemo.common.entity.UserParamEntity;
import com.zy.mydemo.common.utils.ResultUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author:zhongyong
 * @Description：
 * @Date：Create in 2020/04/28
 */
@RestController
@RequestMapping("api/user")
public class UserController {

    @Autowired
    UserService userService;

    @RequestMapping("/doLogin")
    public String doLogin(String loginId, String password, int rememberMe) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(loginId, password);
        token.setRememberMe(rememberMe == 1);

        try {
            subject.login(token);
        } catch (UnknownAccountException e) {
            return ResultUtils.error("用户不存在").toString();
        } catch (IncorrectCredentialsException e) {
            return ResultUtils.error("密码错误").toString();
        }

        return ResultUtils.success("登录成功").toString();
    }

    @RequestMapping("/doLogout")
    public String doLogout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return ResultUtils.success("登出成功").toString();
    }

    @RequestMapping("/addUser")
    public String addUser(UserEntity user) {

        return null;
    }

    @RequestMapping("/getUserList")
    public String getUserList(UserParamEntity param, int pageIndex, int pageSize) {
        System.out.println(param);
        ResultUtils res = userService.getList(param, pageIndex, pageSize);
        System.out.println(res);
        return res.toString();
    }
}
